import Axios from "axios";
import { Message } from "element-ui";
import envConfig from "./env";
import router from '../src/router/index'

// axios的实例
const service = Axios.create({
    baseURL:envConfig.prod.baseURL,
    timeout:5000
})
// 创建请求拦截器
service.interceptors.request.use(config=>{
    if(config.url!=='login'){
        const token = sessionStorage.getItem('token')
        token && (config.headers.Authorization=token)
    }
    return config
},error=>{
    return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res=>{
    const { meta:{msg,status:code},data:result} = res.data

    const successArr = [200,201,204]
    if(successArr.includes(code)){
        Message({
            message:msg,
            type:'success'
        })

        if(res.config.url==='/login'){
            sessionStorage.setItem('token',result.token)
        }
        return result
    }

    Message({
        message:msg,
        type:'error'
    })

    if(msg === '无效token'){
        router.replace('/')
    }

    return Promise.reject(msg);
},error=>{
    return Promise.reject(error)
})

export default service